package com.cjr.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author chenjr16@meicloud.com
 * @Description:
 * @ClassName: LoginInterceptor
 * @date 2020-5-13 16:19
 */
@Configuration
public class LoginInterceptor extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptorAdapter() {

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                     Object handler) throws Exception {
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("username");
                String password = (String) session.getAttribute("password");
                System.out.println("username = " + username + ";password = " + password);
                System.out.println("sessionId = " + session.getId());
                if ("admin".equals(username) && "admin".equals(password)) {
                    return true;
                } else {
                   // response.sendRedirect("/index.html");
                    return false;
                }
            }
        }).addPathPatterns("/*").excludePathPatterns("/login", "/error");
    }
}
